<template>
    <div id="container">
        <a-page-header style="border: 1px solid rgb(235, 237, 240)" title="数据库" @back="() => router.back()">
            <template #extra>
                <!-- <a-button type="primary" @click="exportData">数据导出</a-button> -->
                <a-button type="primary" @click="deleteData">重置数据库</a-button>
                <a-button type="primary" @click="deleteDeviceOther">清空其他表</a-button>
                <a-button type="primary" @click="reStartTaks">重启任务</a-button>
            </template>
        </a-page-header>
        <a-list size="large" bordered :data-source="tableNames">
            <template #renderItem="{ item }">
                <a-list-item @click="lookDBInfo(item)">
                    {{ item }}
                </a-list-item>
            </template>
        </a-list>
    </div>
</template>
<script setup lang="ts">
import { useRouter } from 'vue-router';
import { isAndroid } from '@/utils/UtilFun';
import { computed, onMounted, onUnmounted, ref } from 'vue';

import { db } from '@/utils/DexieDB'

// console.log('db', db);
const router = useRouter();

const tableNames = db.tables.map(table => table.name);
console.log(tableNames);




async function exportData() {
    if (isAndroid()) {
        window.ClosetAndroid.exportData()
    }
}

// 删除数据库
async function deleteData() {
    db.delete().then(async () => {
        router.push('/Home').then(() => {
            router.go(0)
            console.log('数据库清空成功');
        })
    })
}
// 清空除device表之外的数据
async function deleteDeviceOther() {
    try {
        // 使用 Promise.all 并行清空所有非 device 表
        const clearPromises = db.tables
            .filter(table => table.name !== 'device')
            .map(table => table.clear());

        Promise.all(clearPromises).then(async () => {
            router.push('/Home').then(() => {
                router.go(0)
                console.log('除 device 表外的所有表清空成功');
            })
        })

    } catch (error) {
        console.error('清空数据失败:', error);
    }
}

// 重启定时任务
async function reStartTaks() {
    db.device.update(1, { IntervalTaskIsRunning: false }).then(async () => {
        router.push('/Home').then(() => {
            router.go(0)
            console.log('除 device 表外的所有表清空成功');
        })
    })
}


function lookDBInfo(tableName: string) {
    console.log('tableName', tableName);
    router.push({ name: 'DBInfo', query: { tableName: tableName } })
}
</script>
<style lang="scss" scoped>
#container {
    width: 100%;
    height: 100vh;
    overflow: hidden;

    :deep(.ant-page-header-back) {
        font-size: .4rem;
    }

    :deep(.ant-page-header-heading-title) {
        font-size: .5rem;
        line-height: .6rem;
    }

    :deep(.ant-list-item) {
        font-size: .5rem;
    }
}
</style>